/**
 * 
 */
package lt.vin.exaatto.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import lt.vin.exaatto.server.PMF;
import lt.vin.exaatto.server.dao.ChatDao;
import lt.vin.exaatto.shared.Chat;

/**
 * @author Vincentas
 *
 */
public class ChatDaoImpl implements ChatDao {

	@Override
	public void save(Chat chat) {
		Chat savedChat = get(chat.getId());
		if (savedChat != null && !savedChat.getOwner().equalsIgnoreCase(chat.getOwner())) {
			return;
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(chat);
		} finally {
			pm.close();
		}		
	}
	
	public Chat get(String chatId) {
		Chat result = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			result = pm.detachCopy(pm.getObjectById(Chat.class, chatId));
		} catch (JDOObjectNotFoundException notFoundException) {
			/*
			 * Ignore and return null
			 */
		} finally {
			pm.close();
		}		
		
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Chat> getChats(String user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Chat.class);
			try {
				query.setFilter("allMembers == userParameter");
				query.declareParameters("String userParameter");
				
				return new ArrayList<Chat>(pm.detachCopyAll((List<Chat>) query.execute(user)));
			} finally {
				query.closeAll();
			}
		} finally {
			pm.close();
		}
	}

	/* (non-Javadoc)
	 * @see lt.vin.exaatto.server.dao.ChatDao#delete(lt.vin.exaatto.shared.Chat)
	 */
	@Override
	public void delete(String chatId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(pm.getObjectById(Chat.class, chatId));
		} finally {
			pm.close();
		}
	}
}
